package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/28 8:54
 */
public class DwdLogApp extends BaseAppV1 {
    
    public static final String PAGE = "page";
    public static final String START = "start";
    public static final String DISPLAY = "display";
    public static void main(String[] args) {
        new DwdLogApp().init(2001, 1, "DwdLogApp", "DwdLogApp", Constant.TOPIC_ODS_LOG);
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    DataStreamSource<String> stream) {
        // 对流进行处理
        // 1. 区别新老客户: 把is_new字段重复赋值
        SingleOutputStreamOperator<JSONObject> validatedStream = distinguishNewOrOld(stream);
        
        // 2. 数据分流
        HashMap<String, DataStream<JSONObject>> threeStreams = splitStream(validatedStream);
        // 3. 不同的数据写入到不同的topic
        writeToKafka(threeStreams);
       
    }
    
    private void writeToKafka(HashMap<String, DataStream<JSONObject>> threeStreams) {
        threeStreams
            .get(PAGE)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
        threeStreams
            .get(START)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        threeStreams
            .get(DISPLAY)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        
    }
    
    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {};
    
        SingleOutputStreamOperator<JSONObject> pageStream = validatedStream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject obj,
                                       Context ctx,
                                       Collector<JSONObject> out) throws Exception {
                // 启动日志 主流   页面日志   曝光日志
                JSONObject start = obj.getJSONObject("start");
                if (start != null) {
                    // 启动日志
                    out.collect(obj);
                } else {
                    JSONObject page = obj.getJSONObject("page");
                    if (page != null) {
                        ctx.output(pageTag, obj);
                    }
                
                    JSONArray displays = obj.getJSONArray("displays");
                    if (displays != null) {
                        // 为了后面的处理方便, 把曝光拆开
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                        
                            display.put("ts", obj.getLong("ts"));
                        
                            display.putAll(obj.getJSONObject("common"));
                            display.putAll(obj.getJSONObject("page"));
    
                            ctx.output(displayTag, display);
                        }
                    }
                }
            }
        });
    
        HashMap<String, DataStream<JSONObject>> result = new HashMap<>();
        result.put(START, pageStream);
        result.put(PAGE, pageStream.getSideOutput(pageTag));
        result.put(DISPLAY, pageStream.getSideOutput(displayTag));
        return result;
    
    }
    
    //
    private SingleOutputStreamOperator<JSONObject> distinguishNewOrOld(DataStreamSource<String> stream) {
        //        区别新老客户
        /*
            如果找到用户的第一次访问记录:
                使用状态来表示是否是第一次
                
                使用事件时间 + 窗口
                
                如何判断是否第一个窗口?
                    第一个窗口中时间戳最小的 is_new 1
                    其他都是0
         */
       return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Boolean> isFirstWindowState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    isFirstWindowState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Boolean>(
                            "isFirstWindowState",
                            Boolean.class
                        ));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 找到第一个窗口, 然后按照时间戳排序, 最小的是设置为1其他为0
                    // 其他的窗口: 全部设置为0
                    if (isFirstWindowState.value() == null) {
                        // 第一个窗口
                        // 更新状态
                        isFirstWindowState.update(true);
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        //                        list.sort((o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        list.sort(Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (int i = 0; i < list.size(); i++) {
                            JSONObject obj = list.get(i);
                            if (i == 0) {
                                obj.getJSONObject("common").put("is_new", "1");
                            }else{
                                obj.getJSONObject("common").put("is_new", "0");
                            }
                            out.collect(obj);
                        }
                        
                    } else {
                        //非第一个窗口
                        for (JSONObject obj : elements) {
                            obj.getJSONObject("common").put("is_new", "0");
                            out.collect(obj);
                            
                        }
                        
                    }
                    
                }
            });
        
    }
}
